(function() {
  var express, fs, iced, mkdirp, moment, path, pgsql, query, router, __iced_k, __iced_k_noop;

  iced = require('iced-runtime');
  __iced_k = __iced_k_noop = function() {};

  express = require('express');

  pgsql = require('pg');

  moment = require('moment');

  fs = require('fs');

  mkdirp = require('mkdirp');

  path = require('path');

  router = express.Router();

  module.exports = router;

  query = function(req, res, next) {
    var client, done, err, limits, offset, result, table_name, today, trlist_table, where_clause, ___iced_passed_deferral, __iced_deferrals, __iced_k;
    __iced_k = __iced_k_noop;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    where_clause = "( o.uuid like $1 or o.notes like $1 or case when t.chnl in (1,4) then json_extract_path_text(t.i_pkt, '42') like $1 or json_extract_path_text(t.i_pkt, '41') like $1 end or case when t2.chnl = 3 then json_extract_path_text(t2.i_pkt, 'merId') like $1 or json_extract_path_text(t2.i_pkt, 'orderId') like $1 end )";
    today = moment().format('YYYY-MM-DD');
    res.locals.start_date = req.body.start_date || req.query.start_date || today;
    res.locals.end_date = req.body.end_date || req.query.end_date || today;
    table_name = 'pay_p2_order_hist';
    trlist_table = 'pay_trlist_hist';
    if (res.locals.start_date === today && res.locals.end_date === today) {
      table_name = 'pay_p2_order';
      trlist_table = 'pay_trlist';
    }
    where_clause += " and o.sys_time::date >= '" + res.locals.start_date + "'";
    where_clause += " and o.sys_time::date <= '" + res.locals.end_date + "'";
    res.locals.status = req.body.status || req.query.status || '';
    if (res.locals.status.length > 0) {
      where_clause += " and o.status = " + res.locals.status;
    }
    (function(_this) {
      return (function(__iced_k) {
        __iced_deferrals = new iced.Deferrals(__iced_k, {
          parent: ___iced_passed_deferral,
          filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/trstat/p2_order.coffee"
        });
        pgsql.connect(settings.pgsql_url, __iced_deferrals.defer({
          assign_fn: (function() {
            return function() {
              err = arguments[0];
              client = arguments[1];
              return done = arguments[2];
            };
          })(),
          lineno: 51
        }));
        __iced_deferrals._fulfill();
      });
    })(this)((function(_this) {
      return function() {
        if (err) {
          done(client);
          return next(err);
        }
        (function(__iced_k) {
          if (!req._export) {
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/trstat/p2_order.coffee"
              });
              client.query("select count(o.*)::int as count from " + table_name + " as o left join " + trlist_table + " as t on t.uuid = o.t60_uuid and t.incoming = true left join " + trlist_table + " as t2 on t2.uuid = o.t40_uuid and t2.incoming = false where " + where_clause, ["%" + res.locals.keyword + "%"], __iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    err = arguments[0];
                    return result = arguments[1];
                  };
                })(),
                lineno: 65
              }));
              __iced_deferrals._fulfill();
            })(function() {
              if (err) {
                done(client);
                return next(err);
              }
              return __iced_k(res.locals.total = result.rows[0].count);
            });
          } else {
            return __iced_k();
          }
        })(function() {
          offset = req._export ? 0 : res.locals.offset;
          limits = req._export ? 100000000 : res.locals.page_rows;
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/trstat/p2_order.coffee"
            });
            client.query("select o.*, case when t.chnl in (1,4) then array[ json_extract_path_text(t.i_pkt, '42'), json_extract_path_text(t.i_pkt, '41'), json_extract_path_text(t.i_pkt, '11'), json_extract_path_text(t.i_pkt, '4'), json_extract_path_text(t.o_pkt, '2'), json_extract_path_text(t.o_pkt, '13'), json_extract_path_text(t.o_pkt, '12'), json_extract_path_text(t.o_pkt, '37'), json_extract_path_text(t.o_pkt, '39'), t.dcflag::text ] end as t60_info, t.notes as t60_notes, case when t2.chnl = 3 then array[ json_extract_path_text(t2.i_pkt, 'merId'), json_extract_path_text(t2.i_pkt, 'termId'), json_extract_path_text(t2.i_pkt, 'orderId'), json_extract_path_text(t2.i_pkt, 'txnAmt'), json_extract_path_text(t2.n_pkt, 'respCode'), json_extract_path_text(t2.o_pkt, 'queryId'), json_extract_path_text(t2.n_pkt, 'traceNo'), json_extract_path_text(t2.i_pkt, 'accNo') ] end as t40_info, t2.notes as t40_notes, t2.n_pkt is not null as t40_confirm from " + table_name + " as o left join " + trlist_table + " as t on t.uuid = o.t60_uuid and t.uuid_no = 1 left join " + trlist_table + " as t2 on t2.uuid = o.t40_uuid and t2.incoming = false and json_extract_path_text(t2.trinfo, 'code')::text = 't40' where " + where_clause + " order by o.serial desc offset $2 limit $3", ["%" + res.locals.keyword + "%", offset, limits], __iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  err = arguments[0];
                  return result = arguments[1];
                };
              })(),
              lineno: 113
            }));
            __iced_deferrals._fulfill();
          })(function() {
            if (err) {
              done(client);
              return next(err);
            }
            done();
            res.locals.records = result.rows;
            return next();
          });
        });
      };
    })(this));
  };

  router.all('/', query, function(req, res, next) {
    res.locals.stat_title = '助农取款代付明细';
    return res.render('trstat/p2_order');
  });

  router.all('/export', function(req, res, next) {
    req._export = true;
    return next();
  });

  router.all('/export', query, function(req, res, next) {
    var dirname, dnfile, err, line, lines, record, today, ___iced_passed_deferral, __iced_deferrals, __iced_k, _i, _len, _ref;
    __iced_k = __iced_k_noop;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    dirname = settings.dnload_path + "/trstat";
    mkdirp.sync(dirname);
    today = moment().format('YYYY-MM-DD');
    dnfile = "" + dirname + "/p2_order-" + today + ".txt";
    lines = [];
    _ref = res.locals.records;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      record = _ref[_i];
      line = "" + (record.sys_time.format('YYYYMMDDHHmmss')) + ",";
      line += "" + (record.t60_info[0] || '') + ",";
      line += "" + (record.t60_info[1] || '') + ",";
      line += "" + (record.t60_info[2] || '') + ",";
      line += "" + (parseInt(record.t60_info[3] || '0') / 100) + ",";
      line += "" + (record.t60_info[4] || '') + ",";
      line += "" + (record.t60_info[5] || '') + ",";
      line += "" + (record.t60_info[6] || '') + ",";
      line += "" + (record.t60_info[7] || '') + ",";
      line += "" + (record.t60_info[8] || '') + ",";
      line += "" + (record.t60_info[9] || '') + ",";
      if (record.t40_info) {
        line += "" + (record.t40_info[0] || '') + ",";
        line += "" + (record.t40_info[1] || '') + ",";
        line += "" + (record.t40_info[2] || '') + ",";
        line += "" + (parseInt(record.t40_info[3] || '0') / 100) + ",";
        line += "" + (record.t40_info[4] || '') + ",";
        line += "" + (record.t40_info[5] || '') + ",";
        line += "" + (record.t40_info[6] || '');
        line += "" + (record.t40_info[7] || '');
      } else {
        line += ",,,,,,,";
      }
      lines.push(line);
    }
    fs.writeFileSync(dnfile, lines.join("\n"));
    (function(_this) {
      return (function(__iced_k) {
        __iced_deferrals = new iced.Deferrals(__iced_k, {
          parent: ___iced_passed_deferral,
          filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/trstat/p2_order.coffee"
        });
        res.download(dnfile, path.basename(dnfile), __iced_deferrals.defer({
          assign_fn: (function() {
            return function() {
              return err = arguments[0];
            };
          })(),
          lineno: 166
        }));
        __iced_deferrals._fulfill();
      });
    })(this)((function(_this) {
      return function() {
        fs.unlink(dnfile);
        return res.end();
      };
    })(this));
  });

}).call(this);
